package com.example.drainage.ui.certupload

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.example.arm.base.BaseActivity
import com.example.arm.http.imageloader.ImageLoader
import com.example.drainage.base.ktexpand.visible
import com.example.drainage.databinding.ActivityCertSupervisionUploadBinding
import com.example.drainage.databinding.ItemCertSupervisionCheckViewBinding
import com.example.drainage.databinding.ItemCertSupervisionUploadPipeStatusBinding
import com.example.drainage.http.imageloader.ImageConfigImpl
import com.example.drainage.http.imageloader.ImageConfigImplBuilder
import com.example.drainage.ui.certupload.dataview.DataSpotBean
import com.example.drainage.ui.certupload.dataview.EditWithCountDataSpot
import com.example.drainage.ui.certupload.dataview.SingleSelectRecyclerDataSpot
import org.kodein.di.instance

/**
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.example.drainage.ui.certupload
 * @createTime 创建时间 ：2021/12/17
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
class CertSupervisionUploadActivity : BaseActivity<ActivityCertSupervisionUploadBinding>() {

    val mImageLoader: ImageLoader<ImageConfigImpl> by instance()

    private val normalCheckList = mutableListOf(
        DataSpotBean("是"),
        DataSpotBean("否"),
    )

    private val effectCheckList = mutableListOf(
        DataSpotBean("良好"),
        DataSpotBean("一般"),
        DataSpotBean("较差"),
        DataSpotBean("停用"),
    )

    companion object {
        private const val requestCodeManager = 10001
        private const val requestCodeInspectors = 10002
    }

    lateinit var registerSignManager: ActivityResultLauncher<Intent>
    lateinit var registerSignInspectors: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerSignManager = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
            object : ActivityResultCallback<ActivityResult> {
                override fun onActivityResult(result: ActivityResult?) {
                    val data = result?.data ?: return
                    loadSignImageVew(data.getStringExtra("file_path")!!, binding.tvSignManager, binding.ivSignManager)
                }

            })
        registerSignInspectors = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
            object : ActivityResultCallback<ActivityResult> {
                override fun onActivityResult(result: ActivityResult?) {
                    val data = result?.data ?: return
                    loadSignImageVew(data.getStringExtra("file_path")!!, binding.tvSignInspectors, binding.ivSignInspectors)
                }

            })
    }

    override fun initView(savedInstanceState: Bundle?): ActivityCertSupervisionUploadBinding {
        return ActivityCertSupervisionUploadBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        binding.apply {
            // 排水户基础信息
            layoutBaseInfo1.tvItemName.text = "排水户名称"
            layoutBaseInfo2.tvItemName.text = "排水户l类型"
            layoutBaseInfo3.tvItemName.text = "排水户等级"
            layoutBaseInfo4.tvItemName.text = "排水户地址"
            layoutBaseInfo5.tvItemName.text = "排水许可证编号"
            layoutBaseInfo6.tvItemName.text = "排水许可证有效期"
            layoutBaseInfo7.tvItemName.text = "所属污水系统"

            // 资料核查
            initCheckViewInfo(layoutMaterialInfo1, "是否有许可证", isNeed = true)
            initCheckViewInfo(layoutMaterialInfo2, "是否有现场接驳核准意见书", isNeed = true)
            initCheckViewInfo(layoutMaterialInfo3, "是否有管网平面图", isNeed = true)
            initCheckViewInfo(layoutMaterialInfo4, "实际情况是否与管网平面图一致--", isNeed = true)

            // 用水信息
            layoutWaterConsumptionInfo1.tvItemName.text = "用水量"
            layoutWaterConsumptionInfo2.tvItemName.text = "生活用水"
            layoutWaterConsumptionInfo3.tvItemName.text = "工业用水"
            layoutWaterConsumptionInfo4.tvItemName.text = "其他"
            layoutWaterConsumptionInfo1.tvItemUnit.text = "吨"
            layoutWaterConsumptionInfo2.tvItemUnit.text = "吨"
            layoutWaterConsumptionInfo3.tvItemUnit.text = "吨"
            layoutWaterConsumptionInfo4.tvItemUnit.text = "吨"
            layoutWaterConsumptionInfo1.tvItemUnit.visibility = View.VISIBLE
            layoutWaterConsumptionInfo2.tvItemUnit.visibility = View.VISIBLE
            layoutWaterConsumptionInfo3.tvItemUnit.visibility = View.VISIBLE
            layoutWaterConsumptionInfo4.tvItemUnit.visibility = View.VISIBLE

            // 预处理设施
            layoutPretreatmentFacilitySepticTankInfo1.tvItemName.text = "化粪池数量"
            initCheckViewInfo(layoutPretreatmentFacilitySepticTankInfo2, "处理效果", effectCheckList)
            layoutPretreatmentFacilityGreaseTrapsInfo1.tvItemName.text = "隔油池数量"
            initCheckViewInfo(layoutPretreatmentFacilityGreaseTrapsInfo2, "处理效果", effectCheckList)
            layoutPretreatmentFacilitySedimentationTanksInfo1.tvItemName.text = "沉淀池个数"
            layoutPretreatmentFacilitySedimentationTanksInfo2.tvItemName.text = "沉淀池级别"
            initCheckViewInfo(layoutPretreatmentFacilitySedimentationTanksInfo3, "是否正常运行")
            layoutPretreatmentFacilityIntegrationInfo1.tvItemName.text = "一体化处理设施"
            initCheckViewInfo(layoutPretreatmentFacilityIntegrationInfo2, "处理效果", effectCheckList)
            initCheckViewInfo(layoutPretreatmentFacilityIntegrationInfo3, "是否有管养台账")

            // 自建设施
            initCheckViewInfo(layoutSelfBuiltFacilitiesInfo1, "项目内部是否已实施雨污分流")
            initCheckViewInfo(layoutSelfBuiltFacilitiesInfo2, "排水设施是否有清疏台账")

            // 描述
            EditWithCountDataSpot(OUT_PUT_KEY_DESC, etDescContent, tvDescCount, "监管描述")

            // 折叠
            ivTitleCollapsed.setOnClickListener { collapsedExpendView(ivTitleCollapsed, llBaseInfo) }
            ivMaterialCollapsed.setOnClickListener { collapsedExpendView(ivMaterialCollapsed, llMaterial) }
            ivWaterConsumptionCollapsed.setOnClickListener {
                collapsedExpendView(
                    ivWaterConsumptionCollapsed,
                    llWaterConsumptionTop,
                    tvSubTitleWater,
                    llWaterConsumptionBottom
                )
            }
            ivPipeCurStatusCollapsed.setOnClickListener {
                collapsedExpendView(
                    ivPipeCurStatusCollapsed,
                    llPipeCurStatusAdd,
                    llPipeCurStatusContent
                )
            }
            ivPretreatmentFacilityCollapsed.setOnClickListener {
                collapsedExpendView(
                    ivPretreatmentFacilityCollapsed,
                    llPretreatmentFacilitySepticTank,
                    llPretreatmentFacilityGreaseTraps,
                    llPretreatmentFacilitySedimentationTanks,
                    llPretreatmentFacilityIntegration,
                )
            }
            ivSelfBuiltFacilitiesCollapsed.setOnClickListener { collapsedExpendView(ivSelfBuiltFacilitiesCollapsed, llSelfBuiltFacilities) }

            tvSignManager.setOnClickListener {
                registerSignManager.launch(Intent(this@CertSupervisionUploadActivity, SignActivity::class.java))
            }
            tvSignInspectors.setOnClickListener {
                registerSignInspectors.launch(Intent(this@CertSupervisionUploadActivity, SignActivity::class.java))
            }

            // 添加监测井
            tvPipeCurStatusAdd.setOnClickListener {
                addPipeStatusView()
            }
        }

        fakeData()
    }

    private fun initCheckViewInfo(
        itemBinding: ItemCertSupervisionCheckViewBinding,
        text: String,
        itemList: MutableList<DataSpotBean> = normalCheckList,
        isNeed: Boolean = false
    ): SingleSelectRecyclerDataSpot {
        itemBinding.tvItemName.text = text
        itemBinding.tvItemNeed.visible = isNeed
        return SingleSelectRecyclerDataSpot(OUT_PUT_KEY_DESC, itemBinding.content, ItemCheckAdapter().apply {
            setNewInstance(itemList)
        }, text)
    }

    private fun addPipeStatusView() {
        if (binding.llPipeCurStatusContent.childCount > 3) {
            Toast.makeText(this, "监测井已添加到最大数量了!", Toast.LENGTH_LONG).show()
            updatePipeStatusCount()
            return
        }

        val pipeStatusItemBinding =
            ItemCertSupervisionUploadPipeStatusBinding.inflate(layoutInflater, binding.llPipeCurStatusContent, true)
        handleNewPipeStatusView(pipeStatusItemBinding)
        updatePipeStatusCount()
    }

    private fun updatePipeStatusCount() {
        if (binding.llPipeCurStatusContent.childCount >= 3) {
            binding.llPipeCurStatusAdd.visibility = View.GONE
        } else {
            binding.llPipeCurStatusAdd.visibility = View.VISIBLE
            val count = 3 - binding.llPipeCurStatusContent.childCount
            binding.tvPipeCurStatusAddTips.text = "当前还可以添加 $count 个检测井"
        }
    }

    private fun handleNewPipeStatusView(pipeStatusItemBinding: ItemCertSupervisionUploadPipeStatusBinding) {
        pipeStatusItemBinding.apply {
            tvPointSortName.text = "检测井${binding.llPipeCurStatusContent.childCount}"
            initCheckViewInfo(
                layoutPipeStatusInfo1, "检测井类型", mutableListOf(
                    DataSpotBean("雨水"),
                    DataSpotBean("污水"),
                    DataSpotBean("雨污合流"),
                )
            )
            layoutPipeStatusInfo2.tvItemName.text = "接驳终点"
            initCheckViewInfo(layoutPipeStatusInfo3, "是否有浮渣垃圾")
            initCheckViewInfo(layoutPipeStatusInfo4, "是否堵塞")
            initCheckViewInfo(layoutPipeStatusInfo5, "晴天是否有水流动", isNeed = true)
            initCheckViewInfo(layoutPipeStatusInfo6, "是否进行水质检测")
            initCheckViewInfo(layoutPipeStatusInfo7, "接驳管段是否淤塞")
            initCheckViewInfo(layoutPipeStatusInfo8, "对周边排水设施是否造成破坏")

            ivClose.setOnClickListener {
                (root.parent as ViewGroup).removeView(root)
                updatePipeStatusCount()
            }

            // 假数据
            tvPipeName.text = "接驳井-污水"
            tvPipeAddress.text = "贯通路18号/益利农五金灯饰城3通94号益利农五金灯饰城3通94号益利农五金灯饰城3通94号"
        }
    }

    private fun fakeData() {
        binding.apply {
            layoutBaseInfo1.tvItemValue.text = "排水户名称"
            layoutBaseInfo2.tvItemValue.text = "排水户l类型"
            layoutBaseInfo3.tvItemValue.text = "排水户等级"
            layoutBaseInfo4.tvItemValue.text = "排水户地址"
            layoutBaseInfo5.tvItemValue.text = "排水许可证编号"
            layoutBaseInfo6.tvItemValue.text = "排水许可证有效期"
            layoutBaseInfo7.tvItemValue.text = "排水许可证有效期"
        }
    }

    private fun collapsedExpendView(imageView: ImageView, vararg viewList: View) {
        imageView.isSelected = !imageView.isSelected
        if (imageView.isSelected) {
            viewList.forEach { it.visibility = View.GONE }
        } else {
            viewList.forEach { it.visibility = View.VISIBLE }
        }

        val startDegrees = if (imageView.isSelected) 0f else 180f
        val endDegrees = if (imageView.isSelected) 180f else 0f
        val rotateAnimation = RotateAnimation(
            startDegrees, endDegrees,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f
        );
        rotateAnimation.duration = 350
        rotateAnimation.fillAfter = true
        imageView.startAnimation(rotateAnimation)
    }

    private fun loadSignImageVew(filePath: String, tvSign: TextView, ivSign: ImageView) {
        mImageLoader.loadImage(this@CertSupervisionUploadActivity, ImageConfigImplBuilder {
            url = filePath
            imageView = ivSign
        })
        tvSign.text = "重签"
    }
}